function rm(id){
    $("#img_"+id).remove();
    $("#pic_"+id).remove();
}
function uploadimg(argument) {
    if ($(argument).val().length > 0) {
        var id = $(argument).attr('id');
        layer.load();
        ajaxFileUpload(id);
    }else {
        alert("请选择图片");
    }
}
function check_b(argument){
    var hasChk = $(argument).is(':checked');
    var check_val = $(argument).attr('check_val');
    var check_id = $(argument).attr('check_id');
    var check_type = $(argument).attr('check_type');
    if(!check_id){
        layer.msg('请在空白处点一下');return;
    }
    if(hasChk){
        if(check_type == 'room'){
            var html ='<div class="right_win" id="right_'+check_id+'"><div class="plug_l" for="exampleInputEmail1">'+check_val+'：</div>'
                +'<input type="hidden" name="check['+check_id+'][tickets_name]" value="'+check_val+'" />'
                +'<div class="row">'
                +'<label for="exampleInputEmail1">价格：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][price]" class="form-control" placeholder="价格"> </div>'
                +'<label for="exampleInputEmail1">成本价：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][cost_price]" class="form-control" placeholder="成本价"> </div>'
                +'<label for="exampleInputEmail1">市场价：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][market_price]" class="form-control" placeholder="市场价"> </div>'
                +'<label for="exampleInputEmail1">数量：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][num]" class="form-control" placeholder="数量"> </div>'
                +'<label for="exampleInputEmail1">床型：</label><div class="col-lf-5"><input name="check['+check_id+'][bed_type]" type="text" class="form-control "  id="exampleInputEmail1" placeholder=""></div> '
                +'<label for="exampleInputEmail1">面积：</label><div class="col-lf-5"><input name="check['+check_id+'][area]" type="text" class="form-control " id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">窗户：</label><span class="radio-inline"><input type="radio" name="check['+check_id+'][window]"   value="有"> 有</span><span class="radio-inline"><input type="radio" name="check['+check_id+'][window]"  value="无"> 无</span></div>'
                +'<div class="input-group"><label for="exampleInputEmail1">支付方式：</label><span class="checkbox-inline"><input type="checkbox" name="check['+check_id+'][pay]"   value="1"> 微信</span><span class="checkbox-inline"><input type="checkbox" name="check['+check_id+'][pay]"  value="2"> 支付宝</span></div>'
                +'<label for="exampleInputEmail1">用餐：</label><div class="col-lf-5"><input name="check['+check_id+'][dining]" type="text" class="form-control " id="exampleInputEmail1" placeholder=""></div> '
                +'<label for="exampleInputEmail1">宽带：</label><div class="col-lf-5"><input name="check['+check_id+'][broadband]" type="text" class="form-control " id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="h"></div><div class="input-group"><label for="exampleInputEmail1">房型图片：</label><div tabindex="500" class="btn btn-primary btn-file"><i class="glyphicon glyphicon-folder-open"></i>&nbsp;  <span class="hidden-xs">上传图片</span><input id="file'+check_id+'" name="file" check_id="'+check_id+'" type="file" multiple="true" onchange="uploadimg(this)"></div></div> '
                +'<div class="h"></div></div><div class="h"></div></div>';
        }
        else if(check_type == 'items'){
            var html ='<div class="right_win" id="right_'+check_id+'"><div class="plug_l" for="exampleInputEmail1">'+check_val+'：</div>'
                +'<input type="hidden" name="check['+check_id+'][items_name]" value="'+check_val+'" />'
                +'<div class="row">'
                +'<label for="exampleInputEmail1">价格：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][price]" class="form-control" placeholder="价格"> </div>'
                +'<label for="exampleInputEmail1">成本价：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][cost_price]" class="form-control" placeholder="成本价"> </div>'
                +'<label for="exampleInputEmail1">市场价：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][market_price]" class="form-control" placeholder="市场价"> </div>'
                +'<div class="input-group"><label for="exampleInputEmail1">费用包含：</label><input name="check['+check_id+'][fee_includes]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">使用人群：</label><input name="check['+check_id+'][applicable]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">使用方法：</label><input name="check['+check_id+'][method]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">退改规则：</label><input name="check['+check_id+'][unsubscribe]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">发票说明：</label><input name="check['+check_id+'][invoice]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">预定须知：</label><input name="check['+check_id+'][information]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">库存：</label><input name="check['+check_id+'][quantity]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'</div><div class="h"></div></div>';
        }
        else{
            var html ='<div class="right_win" id="right_'+check_id+'"><div class="plug_l" for="exampleInputEmail1">'+check_val+'：</div>'
                +'<input type="hidden" name="check['+check_id+'][tickets_name]" value="'+check_val+'" />'
                +'<div class="row">'
                +'<label for="exampleInputEmail1">价格：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][price]" class="form-control" placeholder="价格"> </div>'
                +'<label for="exampleInputEmail1">成本价：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][cost_price]" class="form-control" placeholder="成本价"> </div>'
                +'<label for="exampleInputEmail1">市场价：</label><div class="col-lf-5"><input type="text" name="check['+check_id+'][market_price]" class="form-control" placeholder="市场价"> </div>'
                +'<div class="input-group"><label for="exampleInputEmail1">费用包含：</label><input name="check['+check_id+'][fee_includes]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">使用人群：</label><input name="check['+check_id+'][applicable]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">使用方法：</label><input name="check['+check_id+'][method]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">退改规则：</label><input name="check['+check_id+'][unsubscribe]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">发票说明：</label><input name="check['+check_id+'][invoice]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'<div class="input-group"><label for="exampleInputEmail1">预定须知：</label><input name="check['+check_id+'][information]" type="text" class="form-control " style="width:400px;" id="exampleInputEmail1" placeholder=""></div> '
                +'</div><div class="h"></div></div>';
        }
        $('.goods_plug').append(html);
    }else{
        $('#right_'+check_id).remove();
    }

}
function change_push(argument) {
    var id = argument.id;
    if(id == ''){
        $.ajax({
            type: "POST",
            url :  "/admin/public/ajax_return",
            data : {
                action : 'add_type',
                good_type : '2',
                name : argument.value
            },
            success: function(data) {
                if (data) {
                    if (data.status == 1) {
                        $(argument).attr('id','tickets_'+data.type_id);
                        $(argument).prev().children().attr('check_id',data.type_id);
                        $(argument).prev().children().attr('check_val',argument.value);
                        alert(c)
                    }
                } else {
                    layer.msg('出现错误');return;
                }
            }
        });

    }

}

function change_item(argument) {
    var id = argument.id;
    if(id == ''){
        $.ajax({
            type: "POST",
            url :  "/admin/public/ajax_return",
            data : {
                action : 'add_type',
                good_type : '3',
                name : argument.value
            },
            success: function(data) {
                if (data) {
                    if (data.status == 1) {
                        $(argument).attr('id','tickets_'+data.type_id);
                        $(argument).prev().children().attr('check_id',data.type_id);
                        $(argument).prev().children().attr('check_val',argument.value);
                        alert(c)
                    }
                } else {
                    layer.msg('出现错误');return;
                }
            }
        });

    }

}

function ajaxFileUpload(id) {
    var name = $('#'+id).val();
    var check_id = $('#'+id).attr('check_id');
    $.ajaxFileUpload
    (
        {
            url: '/admin/public/upload', //用于文件上传的服务器端请求地址
            secureuri: false, //一般设置为false
            fileElementId: id, //文件上传空间的id属性  <input type="file" id="file" name="file" />
            dataType: 'json', //返回值类型 一般设置为json
            success: function (data, status)  //服务器成功响应处理函数
            {
                layer.closeAll('loading');
                if(data.status == 1){
                    if(check_id != undefined){
                        var html = '<span id="pic"><img data-src="holder.js/140x140" class="img-circle" alt="140x140" src="'+data.path+'" data-holder-rendered="true" style="width: 140px; height: 140px;">';
                        html = html+'<input type="hidden" name="check['+check_id+'][room_pic][]"  value="'+data.pic_id+'" /></span>';
                        $('#'+id).parent().parent().parent().append(html);
                    }else{
                        var html = '<span id="pic"><img data-src="holder.js/140x140" class="img-circle" alt="140x140" src="'+data.path+'" data-holder-rendered="true" style="width: 140px; height: 140px;">';
                        html = html+'<input type="hidden" name="pics[]"  value="'+data.pic_id+'" /></span>';
                        $('.imgw').append(html);
                    }
                }

            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
                alert(e);
            }
        }
    )
    return false;
}

$(function(){
    // $('.cale').fullCalendar({
    //     header: {
    //         left: 'prev,next today',
    //         center: 'title',
    //         right: 'month'
    //     },
    //     monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
    //     monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
    //     dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
    //     dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
    //     today: ["今天"],
    //     firstDay: 1,
    //     buttonText: {
    //         today: '今天',
    //         month: '月',
    //         week: '周',
    //         day: '日',
    //         prev: '上一月',
    //         next: '下一月'
    //     },
    //     editable: true,
    //     dragOpacity: {
    //         agenda: .5,
    //         '': .6
    //     },
    //     dayClick: function(date, allDay, jsEvent, view) {
    //         //var toDay = CurentTime();
    //         var selDate =$.fullCalendar.formatDate(date,'yyyy-MM-dd');
    //         var skustock = $(this).children(".day_table").attr('data-stock');
    // 	alert(selDate);
    // 	str = '<div class="addsku">'
    // 	    + '<form role="form" enctype="multipart/form-data" action="" method="GET">'
    //             + '<div class="form-group"><label >开始时间</label><input id="start_time"  style="width:300px" class="form-control datepicker" data-format="YYYY-MM-DD" name="start_time" value="" placeholder="创建日期起始时间"></div>'
    //             + '<div class="form-group"><label >结束时间</label><input id="end_time" style="width:300px" class="form-control datepicker" data-format="YYYY-MM-DD" name="end_time" value="" placeholder="创建日期结束时间"></div>'
    //             + '<div class="input-group"><button class="btn btn-info btn-block" type="submit">提交</button></div>'
    //             + '</form>'
    // 	    + '</div>';
    // 	layer.open({
    //             type: 1,
    // 		title:'添加销售计划',
    //             content: str
    //         });
    // 	 $('#start_time').datetimepicker();
    // 	 $('#end_time').datetimepicker();
    //     },
    // });
    $('#addtickets').click(function(){
        var html = '<div class="col-lf-6"><div class="input-group"><span class="input-group-addon"><input id="" checknp="box" onchange="check_b(this)" type="checkbox"></span><input type="text" id="" onchange="change_push(this)" class="form-control"></div></div>';
        $("#ticketsinput").append(html);
    });
    $('#additems').click(function(){
        var html = '<div class="col-lf-6"><div class="input-group"><span class="input-group-addon"><input id="" checknp="box" check_type="items" onchange="check_b(this)" type="checkbox"></span><input type="text" id="" onchange="change_item(this)" class="form-control"></div></div>';
        $("#ticketsinput").append(html);
    });
    $('#addroom').click(function(){
        var html = '<div class="col-lf-6"><div class="input-group"><span class="input-group-addon"><input id="" checknp="box" check_type="room" onchange="check_b(this)" type="checkbox"></span><input type="text" id="" onchange="change_push(this)" class="form-control"></div></div>';
        $("#ticketsinput").append(html);
    });
    $('#form1').submit(function (e) {
        e.preventDefault();
        $.post("/admin/goodstickets/save",
            $(this).serialize(),
            function(response){
                if(response.status == 0){
                    layer.msg(response.info);
                }else{
                    if(response.url == 'ref'){
                        window.location.reload();
                    }else{
                        window.location.href=response.url;
                    }

                }
            }
        )
    });
    $('#form2').submit(function (e) {
        e.preventDefault();
        $.post("/admin/goodshotel/save",
            $(this).serialize(),
            function(response){
                if(response.status == 0){
                    layer.msg(response.info);
                }else{
                    if(response.url == 'ref'){
                        window.location.reload();
                    }else{
                        window.location.href=response.url;
                    }
                }
            }
        )

    })
    $('#form3').submit(function (e) {
        e.preventDefault();
        $.post("/admin/goodsproducts/save",
            $(this).serialize(),
            function(response){
                if(response.status == 0){
                    layer.msg(response.info);
                }else{
                    if(response.url == 'ref'){
                        window.location.reload();
                    }else{
                        window.location.href=response.url;
                    }
                }
            }
        )

    })
});


/*
 * 地址联动选择
 * input不为空时出现编辑按钮，点击按钮进行联动选择
 *
 * 使用范例：
 * [html]
 * <input id="region" name="region" type="hidden" value="" >
 * [javascrpt]
 * $("#region").nc_region();
 *
 * 默认从cache读取地区数据，如果需从数据库读取（如后台地区管理），则需设置定src参数
 * $("#region").nc_region({{src:'db'}});
 *
 * 如需指定地区下拉显示层级，需指定show_deep参数，默认未限制
 * $("#region").nc_region({{show_deep:2}}); 这样最多只会显示2级联动
 *
 * 系统分自动将已经选择的地区ID存放到ID依次为_area_1、_area_2、_area_3、_area_4、_area的input框中
 * _area存放选中的最后一级ID
 * 这些input框需要手动在模板中创建
 *
 * 取得已选值
 * $('#region').val() ==> 河北 石家庄市 井陉矿区
 * $('#region').fetch('islast')  ==> true; 如果非最后一级，返回false
 * $('#region').fetch('area_id') ==> 1127
 * $('#region').fetch('area_ids') ==> 3 73 1127
 * $('#region').fetch('selected_deep') ==> 3 已选择分类的深度
 * $("#region").fetch('area_id_1') ==> 3
 * $("#region").fetch('area_id_2') ==> 73
 * $("#region").fetch('area_id_3') ==> 1127
 * $("#region").fetch('area_id_4') ==> ''
 */

(function($) {
    $.fn.nc_region = function(options) {
        var $region = $(this);
        var settings = $.extend({}, {
            area_id: 0,
            region_span_class: "_region_value",
            src: "cache",
            show_deep: 0,
            btn_style_html: "",
            tip_type: ""
        }, options);
        settings.islast = false;
        settings.selected_deep = 0;
        settings.last_text = "";
        this.each(function() {
            var $inputArea = $(this);
            if ($inputArea.val() === "") {
                initArea($inputArea)
            } else {
                var $region_span = $('<span id="_area_span" class="' + settings.region_span_class + '">' + $inputArea.val() + "</span>");
                var $region_btn = $('<input type="button" class="input-btn" ' + settings.btn_style_html + ' value="编辑" />');
                $inputArea.after($region_span);
                $region_span.after($region_btn);
                $region_btn.on("click", function() {
                    $region_span.remove();
                    $region_btn.remove();
                    initArea($inputArea)
                });
                settings.islast = true
            }
            this.settings = settings;
            if ($inputArea.val() && /^\d+$/.test($inputArea.val())) {
                $.getJSON("/admin/public/area_show/area_id/" + $inputArea.val(), function(data) {
                    $("#_area_span").html(data.text == null ? "无" : data.text)
                })
            }
        });

        function initArea($inputArea) {
            settings.$area = $("<select class='form-control fl'  style='width:100px'  ></select>");
            $inputArea.before(settings.$area);
            loadAreaArray(function() {
                loadArea(settings.$area, settings.area_id)
            })
        }
        function loadArea($area, area_id) {
            if ($area && nc_a[area_id].length > 0) {
                var areas = [];
                areas = nc_a[area_id];
                if (settings.tip_type && settings.last_text != "") {
                    $area.append("<option value=''>" + settings.last_text + "(*)</option>")
                } else {
                    $area.append("<option value=''>-请选择-</option>")
                }
                for (i = 0; i < areas.length; i++) {
                    $area.append("<option value='" + areas[i][0] + "'>" + areas[i][1] + "</option>")
                }
                settings.islast = false
            }
            $area.on("change", function() {
                var region_value = "",
                    area_ids = [],
                    selected_deep = 1;
                $(this).nextAll("select").remove();
                $region.parent().find("select").each(function() {
                    if ($(this).find("option:selected").val() != "") {
                        region_value += $(this).find("option:selected").text() + " ";
                        area_ids.push($(this).find("option:selected").val())
                    }
                });
                settings.selected_deep = area_ids.length;
                settings.area_ids = area_ids.join(" ");
                $region.val(region_value);
                settings.area_id_1 = area_ids[0] ? area_ids[0] : "";
                settings.area_id_2 = area_ids[1] ? area_ids[1] : "";
                settings.area_id_3 = area_ids[2] ? area_ids[2] : "";
                settings.area_id_4 = area_ids[3] ? area_ids[3] : "";
                settings.last_text = $region.prevAll("select").find("option:selected").last().text();
                var area_id = settings.area_id = $(this).val();
                if ($('#_area_1').length > 0) $("#_area_1").val(settings.area_id_1);
                if ($('#_area_2').length > 0) $("#_area_2").val(settings.area_id_2);
                if ($('#_area_3').length > 0) $("#_area_3").val(settings.area_id_3);
                if ($('#_area_4').length > 0) $("#_area_4").val(settings.area_id_4);
                if ($('#_area').length > 0) $("#_area").val(settings.area_id);
                if ($('#_areas').length > 0) $("#_areas").val(settings.area_ids);
                if (settings.show_deep > 0 && $region.prevAll("select").size() == settings.show_deep) {
                    settings.islast = true;
                    if (typeof settings.last_click == 'function') {
                        settings.last_click(area_id);
                    }
                    return
                }
                if (area_id > 0) {
                    if (nc_a[area_id] && nc_a[area_id].length > 0) {
                        var $newArea = $("<select class='form-control fl' style='width:100px' ></select>");
                        $(this).after($newArea);
                        loadArea($newArea, area_id);
                        settings.islast = false
                    } else {
                        settings.islast = true;
                        if (typeof settings.last_click == 'function') {
                            settings.last_click(area_id);
                        }
                    }
                } else {
                    settings.islast = false
                }
                if ($('#islast').length > 0) $("#islast").val("");
            })
        }
        function loadAreaArray(callback) {
            if (typeof nc_a === "undefined") {
                $.getJSON("/admin/public/json_area", function(data) {
                    nc_a = data;
                    callback()
                })
            } else {
                callback()
            }
        }
        if (typeof jQuery.validator != 'undefined') {
            jQuery.validator.addMethod("checklast", function(value, element) {
                return $(element).fetch('islast');
            }, "请将地区选择完整");
        }
    };
    $.fn.fetch = function(k) {
        var p;
        this.each(function() {
            if (this.settings) {
                p = eval("this.settings." + k);
                return false
            }
        });
        return p
    }
})(jQuery);
